const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

/**
 * 获取所有部门
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAllDepartments = async (req, res) => {
  try {
    const departments = await prisma.department.findMany({
      include: {
        _count: {
          select: {
            users: true
          }
        }
      }
    });
    
    // 格式化返回数据，添加用户数量
    const formattedDepartments = departments.map(dept => ({
      id: dept.id,
      name: dept.name,
      description: dept.description,
      userCount: dept._count.users,
      createdAt: dept.createdAt,
      updatedAt: dept.updatedAt
    }));
    
    return res.json({
      status: 'success',
      data: formattedDepartments
    });
  } catch (error) {
    console.error('获取部门列表失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '获取部门列表失败',
      error: error.message
    });
  }
};

/**
 * 获取单个部门
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getDepartmentById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const department = await prisma.department.findUnique({
      where: { id: parseInt(id) },
      include: {
        users: {
          select: {
            id: true,
            username: true,
            name: true
          }
        },
        _count: {
          select: {
            users: true
          }
        }
      }
    });
    
    if (!department) {
      return res.status(404).json({
        status: 'error',
        message: '部门不存在'
      });
    }
    
    // 格式化返回数据
    const formattedDepartment = {
      id: department.id,
      name: department.name,
      description: department.description,
      userCount: department._count.users,
      users: department.users,
      createdAt: department.createdAt,
      updatedAt: department.updatedAt
    };
    
    return res.json({
      status: 'success',
      data: formattedDepartment
    });
  } catch (error) {
    console.error('获取部门失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '获取部门失败',
      error: error.message
    });
  }
};

/**
 * 创建部门
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.createDepartment = async (req, res) => {
  try {
    const { name, description } = req.body;
    
    // 验证必填字段
    if (!name) {
      return res.status(400).json({
        status: 'error',
        message: '部门名称为必填项'
      });
    }
    
    // 检查名称是否已存在
    const existingDepartment = await prisma.department.findUnique({
      where: { name }
    });
    
    if (existingDepartment) {
      return res.status(400).json({
        status: 'error',
        message: '部门名称已存在'
      });
    }
    
    // 创建部门
    const newDepartment = await prisma.department.create({
      data: {
        name,
        description
      }
    });
    
    return res.status(201).json({
      status: 'success',
      message: '部门创建成功',
      data: newDepartment
    });
  } catch (error) {
    console.error('创建部门失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '创建部门失败',
      error: error.message
    });
  }
};

/**
 * 更新部门
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateDepartment = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description } = req.body;
    
    // 检查部门是否存在
    const department = await prisma.department.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!department) {
      return res.status(404).json({
        status: 'error',
        message: '部门不存在'
      });
    }
    
    // 如果更改名称，检查是否已存在
    if (name && name !== department.name) {
      const existingDepartment = await prisma.department.findUnique({
        where: { name }
      });
      
      if (existingDepartment) {
        return res.status(400).json({
          status: 'error',
          message: '部门名称已存在'
        });
      }
    }
    
    // 准备更新数据
    const updateData = {};
    
    if (name) updateData.name = name;
    if (description !== undefined) updateData.description = description;
    
    // 更新部门
    const updatedDepartment = await prisma.department.update({
      where: { id: parseInt(id) },
      data: updateData
    });
    
    return res.json({
      status: 'success',
      message: '部门更新成功',
      data: updatedDepartment
    });
  } catch (error) {
    console.error('更新部门失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '更新部门失败',
      error: error.message
    });
  }
};

/**
 * 删除部门
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.deleteDepartment = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查部门是否存在
    const department = await prisma.department.findUnique({
      where: { id: parseInt(id) },
      include: {
        _count: {
          select: {
            users: true
          }
        }
      }
    });
    
    if (!department) {
      return res.status(404).json({
        status: 'error',
        message: '部门不存在'
      });
    }
    
    // 检查是否有用户关联此部门
    if (department._count.users > 0) {
      return res.status(400).json({
        status: 'error',
        message: '无法删除部门，请先移除关联的用户'
      });
    }
    
    // 删除部门
    await prisma.department.delete({
      where: { id: parseInt(id) }
    });
    
    return res.json({
      status: 'success',
      message: '部门删除成功'
    });
  } catch (error) {
    console.error('删除部门失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '删除部门失败',
      error: error.message
    });
  }
}; 